package com.easylinkin.linkappapi.circuit.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.circuit.dto.RailGiveAlarmTypeConfigEnum;
import com.easylinkin.linkappapi.circuit.dto.RailLinkappAiHostRecordDTO;
import com.easylinkin.linkappapi.circuit.entity.RailLinkappAiHostRecord;
import com.easylinkin.linkappapi.circuit.mapper.RailGiveSystemAlarmMapper;
import com.easylinkin.linkappapi.circuit.mapper.RailLinkappAiHostRecordMapper;
import com.easylinkin.linkappapi.circuit.service.IRailGiveAlarmTypeConfigService;
import com.easylinkin.linkappapi.circuit.service.IRailGiveSystemAlarmService;
import com.easylinkin.linkappapi.circuit.service.IRailLinkappAiHostRecordService;
import com.easylinkin.linkappapi.circuit.vo.RailLinkappAiHostRecordVO;
import com.easylinkin.linkappapi.circuit.vo.RailLinkappAiHostRecordStatisticsVO;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.config.entity.SysDict;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import com.easylinkin.linkappapi.config.service.SysDictItemService;
import com.easylinkin.linkappapi.config.service.SysDictService;
import com.easylinkin.linkappapi.device.constant.DeviceConstant;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.mechanical.entity.EquipmentLocation;
import com.easylinkin.linkappapi.openapi.dto.DatapushDTO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.misc.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author lyk
 * @date 2025/6/23 下午 1:45
 */
@Service
@Slf4j
public class RailLinkappAiHostRecordServiceImpl extends ServiceImpl<RailLinkappAiHostRecordMapper, RailLinkappAiHostRecord> implements IRailLinkappAiHostRecordService {
    @Autowired
    private SysDictItemService dictItemService;
    @Autowired
    private SysDictItemService sysDictItemService;
    @Autowired
    private IRailGiveSystemAlarmService railGiveSystemAlarmService;
    @Autowired
    private RailGiveSystemAlarmMapper railGiveSystemAlarmMapper;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;
    @Override
    public Map<String, Object> aiBehaviorAlerts() {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        //打架
        //查询字典
        List<SysDictItem> ai_rule_type = dictItemService.selectByDictItems("ai_rule_type");
        List<Map<String,Object>> LeftList = new ArrayList<>();
        List<Map<String,Object>> pieChart = new ArrayList<>();
        //左侧行为
        List<String> arrs_l = Arrays.asList("打架","未戴安全帽","吸烟","未穿反光服");
        for (SysDictItem dict:ai_rule_type){
            if (arrs_l.contains(dict.getItemText())){
                Map<String, Object> maps = new HashMap<>();
                maps.put("name",dict.getItemText());
                maps.put("sum", baseMapper.selectByAiRuleTypeAndTenantId(tenantId,dict.getItemValue()));
                LeftList.add(maps);
            }
        }
        //未系安全带
        Integer bd_s = baseMapper.selectByAiRuleTypeAndTenantId(tenantId, "10");
        Integer aqs_s = baseMapper.selectByAiRuleTypeAndTenantId(tenantId, "11");
        Map<String, Object> yh1_map = new HashMap<>();
        yh1_map.put("name","未系安全带");
        yh1_map.put("sum",bd_s+aqs_s);
        LeftList.add(yh1_map);
        //右侧行为
        List<String> arrs_r = Arrays.asList("区域入侵","举手求救","行为识别","跌倒","外来人员识别");
        for (SysDictItem dict:ai_rule_type){
            if (arrs_r.contains(dict.getItemText())){
                Map<String, Object> maps = new HashMap<>();
                maps.put("name",dict.getItemText());
                maps.put("sum", baseMapper.selectByAiRuleTypeAndTenantId(tenantId,dict.getItemValue()));
                pieChart.add(maps);
            }
        }
        //烟火识别
        //明火
        // Integer mh_s = baseMapper.selectByAiRuleTypeAndTenantId(tenantId, "06");
        // Integer yw_s = baseMapper.selectByAiRuleTypeAndTenantId(tenantId, "07");
        // 使用railGiveSystemAlarmMapper计算，tenantId，时间是创建时间，category = 5
        List<com.easylinkin.linkappapi.circuit.dto.AlarmTypeCount> alarmTypeCounts = railGiveSystemAlarmMapper.alarmTypeCount(tenantId, "5", null, null, null);
        Map<String, Integer> alarmCountMap = new HashMap<>();
        for (com.easylinkin.linkappapi.circuit.dto.AlarmTypeCount count : alarmTypeCounts) {
            alarmCountMap.put(count.getAlarmType(), count.getCount());
        }
        Integer mh_s = alarmCountMap.getOrDefault("25", 0); // 烟火对应AlarmType_25
/*        Integer yw_s = alarmCountMap.getOrDefault("25", 0); // 烟火统一用AlarmType_25*/
        Map<String, Object> yh_map = new HashMap<>();
        yh_map.put("name","烟火识别");
        yh_map.put("sum",mh_s);
        pieChart.add(yh_map);
        Map<String, Object> result = new HashMap<>();
        result.put("pieChart",pieChart);
        result.put("LeftList",LeftList);
        return result;
    }

    @Override
    public Map<String, Object> nowDaySnapTotleLineChart() {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        List<String> hours = DateUtil.getHoursFrom1AM();
        RailLinkappAiHostRecordDTO dto = new RailLinkappAiHostRecordDTO();
        dto.setStartCreateH(hours.get(0));
        dto.setEndCreateH(hours.get(hours.size() - 1));
        dto.setTenantId(tenantId);
        List<RailLinkappAiHostRecordVO> data = baseMapper.getList(dto);
        Map<String, Integer> maps_s = new HashMap<>();
        for (RailLinkappAiHostRecordVO vo:data){
            String date_k = DateUtil.getDateFromFormatStr(vo.getCreateTime(), DateUtil.DATE_TIME_FORMAT_HOUR);
            Integer sum = maps_s.get(date_k);
            if (Objects.isNull(sum)){
                sum = 1;
                maps_s.put(date_k,sum);
            }else{
                sum++;
                maps_s.put(date_k,sum);
            }
        }
        Integer sums = 0;
        List<String> abscissa = new ArrayList<>();
        List<Integer> sum = new ArrayList<>();
        for (String cm:hours){
            Integer integer = maps_s.get(cm);
            if (Objects.isNull(integer)){
                integer = 0;
            }
            sum.add(integer);
            Date dateFromFormatStr = DateUtil.getDateFromFormatStr(cm , DateUtil.DATE_TIME_FORMAT_HOUR);
            String date_k = DateUtil.getDateFromFormatStr(dateFromFormatStr, DateUtil.DATE_TIME_FORMAT_HM);
            abscissa.add(date_k);
            sums = sums + integer;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("abscissa",abscissa);
        result.put("sums",sum);
        result.put("sum",sums);
        return result;
    }

    @Override
    public List<RailLinkappAiHostRecordVO> getList(RailLinkappAiHostRecordDTO dto) {
        return baseMapper.getList(dto);
    }

    @Override
    public IPage<RailLinkappAiHostRecordVO> selectPage(Page page, RailLinkappAiHostRecordDTO customQueryParams) {
        customQueryParams.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        IPage<RailLinkappAiHostRecordVO> page1 = baseMapper.getList(page, customQueryParams);
        return page1;
    }

    @Override
    public RailLinkappAiHostRecordStatisticsVO getStatistics() {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();

        RailLinkappAiHostRecordStatisticsVO statisticsVO = new RailLinkappAiHostRecordStatisticsVO();

        // 获取当日统计数量
         Long todayCount = baseMapper.countTodayByTenantId(tenantId);
        statisticsVO.setTodayCount(todayCount);

        // 获取近7日统计数量
        Long last7DaysCount = baseMapper.countLast7DaysByTenantId(tenantId);
        statisticsVO.setLast7DaysCount(last7DaysCount);

        return statisticsVO;
    }

    @Override
    public RailLinkappAiHostRecordVO getNowByOne() {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        //设置类型id
        List<String> types = new ArrayList<>();
        types.add("555");//外来人员识别
        types.add("06");//烟火识别
        types.add("07");//烟火识别
        types.add("03");//区域入侵
        types.add("09");//举手求救
        types.add("04");//跌倒
        //只查询一小时之内的数据
        return baseMapper.getNowHourByOne(tenantId,types);
    }

    @Override
    public List<RailLinkappAiHostRecordVO> codeByNewRecords(String tenantId, List<String> codes) {
        return baseMapper.codeByNewRecords(tenantId,codes);
    }

    @Override
    public Map<String, Object> byStatisticsLins(String tenantId,  List<Device> devices,RailLinkappAiHostRecordDTO dto) {
        List<Long> sums = new ArrayList<>();
        List<String> csc = new ArrayList<>();
        List<String> codes = new ArrayList<>();
        /*for (Device e:devices){
            codes.add(e.getCode());
        }*/
        /**
         * 聚合查询摄像头名称
         */
        String nameGroupBy = baseMapper.getNameGroupBy(tenantId);
        for (String name : nameGroupBy.split(",")){
            //csc.add(name);
            codes.add(name);
        }
        if (codes.size() == 0){
            Map<String,Object> res =  new HashMap<>();
            res.put("sums",sums);
            res.put("csc",csc);
            return res;
        }
        List<RailLinkappAiHostRecordStatisticsVO>  sts = null;
        if (dto.getType().equals("1")){
            sts =   baseMapper.countName7DaysByTenantId(tenantId,codes);
        }else if (dto.getType().equals("2")) {
            sts =   baseMapper.countName30DaysByTenantId(tenantId,codes);
        }
        Map<String,Long> transMap = new HashMap<>();
        if (!Objects.isNull(sts)){
           for (RailLinkappAiHostRecordStatisticsVO svo:sts){
               transMap.put(svo.getDevCode(),svo.getDataCount());
           }
        }
        for (String e:codes){
            csc.add(e);
            sums.add(Objects.isNull(transMap.get(e))?0l:transMap.get(e));
        }
        Map<String,Object> res =  new HashMap<>();
        res.put("sums",sums);
        res.put("csc",csc);
        return res;
    }

    @Override
    public Map<String, Object> getViolationBehaviorPieChart() {
        List<Map<String,Object>> pieChart =  new ArrayList<>();
        List<SysDictItem> ai_rule_type = dictItemService.selectByDictItems("ai_rule_type");
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        //烟火
        Integer mh_s = baseMapper.selectByAiRuleTypeAndTenantId(tenantId, "06");
        Integer yw_s = baseMapper.selectByAiRuleTypeAndTenantId(tenantId, "07");
        Map<String, Object> yhsb_map = new HashMap<>();
        yhsb_map.put("name","烟火识别");
        yhsb_map.put("sum",mh_s+yw_s);
        pieChart.add(yhsb_map);
        // 违规行为
        List<String> arrs_r = Arrays.asList("区域入侵","举手求救","跌倒","外来人员识别");
        for (SysDictItem dict:ai_rule_type) {
            if (arrs_r.contains(dict.getItemText())) {
                Map<String, Object> maps = new HashMap<>();
                maps.put("name", dict.getItemText());
                maps.put("sum", baseMapper.selectByAiRuleTypeAndTenantId(tenantId, dict.getItemValue()));
                pieChart.add(maps);
                //172.16.10.25
            }
        }
        //未系安全带
        Integer bd_s = baseMapper.selectByAiRuleTypeAndTenantId(tenantId, "10");
        Integer aqs_s = baseMapper.selectByAiRuleTypeAndTenantId(tenantId, "11");
        //违规行为
        arrs_r = Arrays.asList("未戴安全帽","未穿反光服","打架","吸烟");
        Integer wgxw_sum = (bd_s+aqs_s);
        for (SysDictItem dict:ai_rule_type) {
            if (arrs_r.contains(dict.getItemText())) {
                Integer integer = baseMapper.selectByAiRuleTypeAndTenantId(tenantId, dict.getItemValue());
                wgxw_sum  = wgxw_sum + integer;
            }
        }
        Map<String, Object> wxaqd_d = new HashMap<>();
        wxaqd_d.put("name","违规行为");
        wxaqd_d.put("sum",wgxw_sum);
        pieChart.add(wxaqd_d);
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("LeftList",pieChart);
        return objectObjectHashMap;
    }

    @Override
    public Map<String, Object> getPrompt(String tenantId) {
        HashMap<String, Object> result_str = new HashMap<>();
        List<String> types = new ArrayList<>();
        types.add("06");//烟火识别
        types.add("07");//烟火识别
        //烟火
        Integer nowDayByOne = baseMapper.getNowDayByOne(tenantId, types);
        if (nowDayByOne>0){
            result_str.put("msg","今日发生多次烟火，请注意规范用电用火等安全事项，保持消防通道畅通！");
            return result_str;
        }
        types = new ArrayList<>();
        types.add("09");//举手求救
        nowDayByOne = baseMapper.getNowDayByOne(tenantId, types);
        if (nowDayByOne>0){
            result_str.put("msg","今日识别到多次举手求救信号，请安全员立即核查作业面人员状态及环境安全！");
            return result_str;
        }
        types = new ArrayList<>();
        types.add("03");//区域入侵
        nowDayByOne = baseMapper.getNowDayByOne(tenantId, types);
        if (nowDayByOne>0){
            result_str.put("msg","今日发生多起区域入侵，请注重区域管理，守护施工安全！");
            return result_str;
        }
        //暂无外来人员识别 （跳过）

        //未带安全帽、未系安全带、未穿反光衣、打架、吸烟
        types = new ArrayList<>();
        types.add("00");//未带安全帽
        types.add("10");//未系安全带
        types.add("11");//未系安全带
        types.add("05");//未穿反光衣
        types.add("08");//打架
        types.add("02");//吸烟
        nowDayByOne = baseMapper.getNowDayByOne(tenantId, types);
        if (nowDayByOne>=30){
            result_str.put("msg","今日识别到多起作业违规行为，请加强安全行为规范，守护施工安全！");
            return result_str;
        }
        //所有告警超过5次
        List<RailLinkappAiHostRecordStatisticsVO> nowDayByAll = baseMapper.getNowDayByAll(tenantId);
        if (nowDayByAll.size()>0){
           for (RailLinkappAiHostRecordStatisticsVO vo:nowDayByAll){
               if (vo.getDataCount()>=5){
                   result_str.put("msg",vo.getChaName()+"视频监控附近识别到多起不规范行为，请加强该视频区域的施工安全！");
                   return result_str;
               }
           }
        }
        result_str.put("msg","");
        return result_str;
    }


    @Override
    public void datapushHandler(DatapushDTO datapushDTO) {

        JSONObject data = datapushDTO.getData();
        // 将查询逻辑放入主线程
        //String device_code = data.getString("device_id");

        Device device = datapushDTO.getDevice_data_latest();
        if (Objects.isNull(device)){
            return;
        }
        if (!DeviceConstant.RailwayDeviceType.AI_RECOGNITION_HOST.getDescription().contains(device.getDeviceUnit().getDeviceTypeName())) {
            return;
        }
        // 规则类型 字典
        String ruleType = data.getString("ruleType");
        if (StringUtils.isEmpty(ruleType)){
            return;
        }
        String eventType = data.getString("eventType");
        SysDictItem sysDictItem_check = sysDictItemService.selectByDictItem("ai_event_type", "1");
        if (!sysDictItem_check.getItemValue().equals(eventType)){
            return;
        }
        String image = data.getString("image");
        String ipcSn = data.getString("ipcSn");
        //摄像头地址
        String ipcAddress = data.getString("ipcAddress");
        String channelStatus = data.getString("channelStatus");
        String channelName = data.getString("channelName");
        //事件类型 字典

        String hasResult = data.getString("hasResult");
        //行为分析数据json
        String behaviour = data.getString("behaviour");
        //获取字典配置
        RailLinkappAiHostRecord aiHostRecord =  new RailLinkappAiHostRecord();
        aiHostRecord.setAiRuleType(ruleType);
        aiHostRecord.setAiEventType(eventType);
        if (!StringUtils.isEmpty(ruleType)){
            SysDictItem sysDictItem = sysDictItemService.selectByDictItem("ai_rule_type", ruleType);
            if (Objects.nonNull(sysDictItem)){
                aiHostRecord.setAiRuleType(sysDictItem.getItemValue());
            }
        }
        if (!StringUtils.isEmpty(eventType)){
            SysDictItem sysDictItem = sysDictItemService.selectByDictItem("ai_event_type", eventType);
            if (Objects.nonNull(sysDictItem)){
                aiHostRecord.setAiEventType(sysDictItem.getItemValue());
            }
        }
        aiHostRecord.setDeviceCode(device.getCode());
        aiHostRecord.setImage(image);
        aiHostRecord.setIpcSn(ipcSn);
        aiHostRecord.setIpcAddress(ipcAddress);
        aiHostRecord.setChannelStatus(channelStatus);
        aiHostRecord.setHasResult(hasResult);
        aiHostRecord.setBehaviourJson(behaviour);
        aiHostRecord.setTenantId(device.getTenantId());
        aiHostRecord.setCreateTime(new Date());
        aiHostRecord.setChannelName(channelName);
        baseMapper.insert(aiHostRecord);
        /**
         * 系统告警_锚点
         */
        if (!StringUtils.isEmpty(ruleType)){
         SysDictItem dictItem =  dictItemService.selectByDictItem("testing_item","1");
         if (Objects.isNull(dictItem)){
             return;
         }
                //违章警告
        railGiveSystemAlarmService
                .datapushHandlerAiData(datapushDTO,dictItem, RailGiveAlarmTypeConfigEnum.AlarmType_24);

        railGiveSystemAlarmService
                .datapushHandlerAiData(datapushDTO,dictItem, RailGiveAlarmTypeConfigEnum.AlarmType_25);

        railGiveSystemAlarmService
                .datapushHandlerAiData(datapushDTO,dictItem, RailGiveAlarmTypeConfigEnum.AlarmType_26);

        railGiveSystemAlarmService
                .datapushHandlerAiData(datapushDTO,dictItem, RailGiveAlarmTypeConfigEnum.AlarmType_27);

        railGiveSystemAlarmService
                .datapushHandlerAiData(datapushDTO,dictItem, RailGiveAlarmTypeConfigEnum.AlarmType_28);


        railGiveSystemAlarmService
                .datapushHandlerAiData(datapushDTO,dictItem, RailGiveAlarmTypeConfigEnum.AlarmType_29);

        railGiveSystemAlarmService
                .datapushHandlerAiData(datapushDTO,dictItem, RailGiveAlarmTypeConfigEnum.AlarmType_30);
        railGiveSystemAlarmService
                .datapushHandlerAiData(datapushDTO,dictItem, RailGiveAlarmTypeConfigEnum.AlarmType_31);
        railGiveSystemAlarmService
                .datapushHandlerAiData(datapushDTO,dictItem, RailGiveAlarmTypeConfigEnum.AlarmType_32);
        railGiveSystemAlarmService
                .datapushHandlerAiData(datapushDTO,dictItem, RailGiveAlarmTypeConfigEnum.AlarmType_33);
        }
        }

    @Override
    public Map<String, Object> getAiAlarmStatistics() {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        Map<String, Object> result = new HashMap<>();

        // 今日告警总次数 - 使用RailLinkappAiHostRecord数据源
        Long todayCount = baseMapper.countTodayByTenantId(tenantId);
        int nowSum = todayCount != null ? todayCount.intValue() : 0;
        result.put("nowSum", nowSum);

        // 昨日告警总次数，用于计算比较昨日的增长
        // 需要添加新的Mapper方法来获取昨日数据
        int yesterdaySum = getYesterdayCount(tenantId);
        int growthSum = nowSum - yesterdaySum;
        result.put("growthSum", growthSum);

        // 近一个月总次数（30天）
        int intervalThirtySum = getLast30DaysCount(tenantId);
        result.put("intervalThirtySum", intervalThirtySum);

        // 累计总次数 - 查询该租户所有AI记录总数
        int sum = getTotalCount(tenantId);
        result.put("sum", sum);

        return result;
    }

    /**
     * 获取昨日AI记录数量
     */
    private int getYesterdayCount(String tenantId) {
        // 使用LambdaQueryWrapper查询昨日数据
        String yesterday = com.easylinkin.linkappapi.common.utils.DateUtil.getLastDays(1);
        com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<RailLinkappAiHostRecord> queryWrapper =
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
        queryWrapper.eq(RailLinkappAiHostRecord::getTenantId, tenantId);
        queryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') = {0}", yesterday);
        return this.count(queryWrapper);
    }

    /**
     * 获取近30天AI记录数量
     */
    private int getLast30DaysCount(String tenantId) {
        String startDate = com.easylinkin.linkappapi.common.utils.DateUtil.getLastDays(29);
        String endDate = com.easylinkin.linkappapi.common.utils.DateUtil.getYYYYMMDDDate(new Date());

        com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<RailLinkappAiHostRecord> queryWrapper =
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
        queryWrapper.eq(RailLinkappAiHostRecord::getTenantId, tenantId);
        queryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') >= {0}", startDate);
        queryWrapper.apply("DATE_FORMAT(create_time, '%Y-%m-%d') <= {0}", endDate);
        return this.count(queryWrapper);
    }

    /**
     * 获取累计总数量
     */
    private int getTotalCount(String tenantId) {
        com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<RailLinkappAiHostRecord> queryWrapper =
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
        queryWrapper.eq(RailLinkappAiHostRecord::getTenantId, tenantId);
        return this.count(queryWrapper);
    }

}
